﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Diagnostics;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Xml;
using System.Xml.Linq;

namespace DukeNUS.FacilitiesPlanning.FPSystem.Data
{

    /// <summary>
    /// The application's database initialization class.
    /// </summary>
    public class DukeNUSDatabaseInitializer : CreateDatabaseIfNotExists<DukeNUSDatabase>
    {

        protected override void Seed(DukeNUSDatabase context)
        {
            base.Seed(context);

            try 
            {
                string path = ConfigurationManager.AppSettings["DBInitializers"];
                XElement xml = XElement.Load(HttpContext.Current.Server.MapPath(path));

                var query = from scripts in xml.Elements("script")
                            select new
                            {
                                Script = (string)scripts
                            };

                using (TransactionScope trans = new TransactionScope())
                {
                    using (DukeNUSDatabase db = new DukeNUSDatabase())
                    {
                        foreach (var script in query)
                        {
                            db.Database.ExecuteSqlCommand(script.Script, "");
                        }

                        db.SaveChanges(); trans.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(GetType().FullName, string.Format("Message: {0}\nStack Trace: {1}", ex.Message, ex.StackTrace), EventLogEntryType.Error);
            }
        }

    }
}